package com.xiangyang.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xiangyang.entity.dto.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Component
public class AnonymousAuthenticationHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("text/html;charset=utf-8");
        ServletOutputStream out = response.getOutputStream();
        String message = "";
        if (authException instanceof BadCredentialsException) {
            message = JSON.toJSONString(Result.error(504,authException.getMessage()),SerializerFeature.DisableCircularReferenceDetect);
        }else if (authException instanceof InternalAuthenticationServiceException) {
            message = JSON.toJSONString(Result.error(504,authException.getMessage()), SerializerFeature.DisableCircularReferenceDetect);
        }else {
            message = JSON.toJSONString(Result.error(504,authException.getMessage()),SerializerFeature.DisableCircularReferenceDetect);
        }
        out.write(message.getBytes("utf-8"));
        out.flush();
        out.close();
    }
}
